<script setup lang="ts">
import {onMounted, onUnmounted, ref} from "vue";
import {invoke} from "@tauri-apps/api/core";
import {message} from "ant-design-vue";
import tool from "./utils/tool";

// 定义 Service 接口，与 Rust 中的结构体对应
interface Service {
  name: string;
  status: string;
  status_text: string;
}

interface ServiceForm {
  name: string;
  auto_start?: boolean;
  description?: string;
}



// 查询服务状态
async function checkServiceStatus(serviceName: String) {
  try {
    const service: Service = await invoke('check_service_status', { serviceName });
    console.log(`服务 ${service.name} 状态: ${service.status_text}`);
    return service;
  } catch (error) {
    console.error(`查询服务 ${serviceName} 状态失败:`, error);
    return null;
  }
}



// 启动服务
async function startService(serviceName: String) {
  try {
    const result = await invoke('start_service', { serviceName });
    console.log(result);
    await refreshServices();
    return true;
  } catch (error) {
    console.error(`启动服务 ${serviceName} 失败:`, error);
    message.error(`启动服务 ${serviceName} 失败，请使用管理员权限启动服务。`)
    return false;
  }
}

// 停止服务
async function stopService(serviceName: String) {
  try {
    const result = await invoke('stop_service', { serviceName });
    console.log(result);
    await refreshServices();
    return true;
  } catch (error) {
    console.error(`停止服务 ${serviceName} 失败:`, error);
    message.error(`停止服务 ${serviceName} 失败，请使用管理员权限启动服务。`)
    return false;
  }
}

// 批量检查所有服务
async function checkAllServices() {
  const services = [];
  let allConfig = tool.serviceConfig.getAll();
  for (const config of allConfig) {
    let name = config.name
    const service = await checkServiceStatus(name);
    if (service) {
      services.push(service);
    }
  }
  return services;
}


// 使用示例
checkAllServices().then(services => {
  console.log('所有服务状态:', services)
  servicesData.value = services
});

// 刷新服务状态
async function refreshServices() {
  servicesData.value = await checkAllServices();
}

const loading = ref(false);
const open = ref(false);
const formData = ref<ServiceForm>();
// 弹出添加服务模态框
const showModal = () => {
  open.value = true;
  formData.value = {auto_start: false, description: "", name: ""}
};
// 删除服务
async function deleteService(name: string) {
  tool.serviceConfig.remove(name);
  await refreshServices();
}
const openUpdateService = (name: string) => {
  open.value = true;
  const config = tool.serviceConfig.getByName(name);
  if (config) {
    formData.value = {
      name: config.name,
      auto_start: config.auto_start,
      description: config.description
    };
  } else {
    formData.value = {
      name: name,
      auto_start: false,
      description: ''
    };
  }
  console.log('更新服务:', formData.value);
};

const handleOk = () => {
  loading.value = true;
  if (formData.value) {
    tool.serviceConfig.addOrUpdate(formData.value);
    refreshServices()
    loading.value = false;
    open.value = false;
  }
};
const handleCancel = () => {
  open.value = false;
};

const servicesData = ref<Service[]>([]);

// 自动刷新相关
let refreshIntervalId: number | null = null;

// 启动自动刷新
const startAutoRefresh = () => {
  // 每5秒刷新一次服务状态
  refreshIntervalId = window.setInterval(refreshServices, 3000);
};

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshIntervalId) {
    clearInterval(refreshIntervalId);
    refreshIntervalId = null;
  }
};

// 组件挂载时启动自动刷新
onMounted(() => {
  startAutoRefresh();
});

// 组件卸载时停止自动刷新
onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<template>
  <main class="container">
    <div style="margin-bottom: 10px">
      <a-space>
        <a-button type="primary" @click="showModal">添加服务</a-button>
      </a-space>
    </div>
    <a-card class="card" v-for="item in servicesData" :key="item.name">
      <a-row :gutter="16" align="middle">
        <a-col :span="8">
          <h2>{{ item.name }}</h2>
        </a-col>
        <a-col :span="8">
          <a-tag :color="item.status === 'running' ? 'green' : 'red'">
            {{ item.status_text }}
          </a-tag>
        </a-col>
        <a-col :span="8">
          <a-space>
            <a-dropdown-button>
              控制
              <template #overlay>
                <a-menu>
                  <a-menu-item key="3">
                    <a-button type="primary" size="middle" @click="startService(item.name)">启动</a-button>
                  </a-menu-item>
                  <a-menu-item key="5">
                    <a-button v-if="item.status === 'running'" @click="stopService(item.name)" type="primary" danger size="middle">停止</a-button>
                  </a-menu-item>
                  <a-menu-item key="1">
                    <a-button type="primary" size="middle" @click="openUpdateService(item.name)">修改</a-button>
                  </a-menu-item>
                  <a-menu-item key="2">
                    <a-button type="primary" size="middle" danger @click="deleteService(item.name)">删除</a-button>
                  </a-menu-item>
                  <a-menu-item key="4"></a-menu-item>
                </a-menu>
              </template>
            </a-dropdown-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
  </main>
  <!-- CSS动画线条 -->
  <div class="animated-line-container">
    <div class="animated-line"></div>
  </div>
  <a-modal v-model:open="open" title="添加服务" @ok="handleOk">
    <template #footer>
      <a-button key="back" @click="handleCancel">关闭</a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">添加</a-button>
    </template>
    <a-form style="padding: 30px" :model="formData" v-if="formData">
      <a-form-item label="服务名称">
        <a-input v-model:value="formData.name" placeholder="请输入服务名称" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>

</style>
<style>
:root {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 24px;
  font-weight: 400;

  color: #0f0f0f;
  background-color: #f6f6f6;

  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-text-size-adjust: 100%;
}

.container {
  margin: 0;
  padding-top: 2vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

.card {
  width: 80vw;
  margin: 5px auto;
}

a {
  font-weight: 500;
  color: #646cff;
  text-decoration: inherit;
}

a:hover {
  color: #535bf2;
}

h1 {
  text-align: center;
}

input,
button {
  border-radius: 8px;
  border: 1px solid transparent;
  padding: 0.6em 1.2em;
  font-size: 1em;
  font-weight: 500;
  font-family: inherit;
  color: #0f0f0f;
  background-color: #ffffff;
  transition: border-color 0.25s;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}

button {
  cursor: pointer;
}

button:hover {
  border-color: #396cd8;
}
button:active {
  border-color: #396cd8;
  background-color: #e8e8e8;
}
@media (prefers-color-scheme: dark) {
  :root {
    color: #f6f6f6;
    background-color: #2f2f2f;
  }

  a:hover {
    color: #24c8db;
  }

  input,
  button {
    color: #ffffff;
    background-color: #0f0f0f98;
  }
  button:active {
    background-color: #0f0f0f69;
  }
}

/* CSS动画线条容器 */
.animated-line-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

/* CSS动画线条 */
.animated-line {
  height: 100%;
  width: 50%;
  background: linear-gradient(90deg, #1890ff, #52c41a);
  box-shadow: 0 0 10px rgba(24, 144, 255, 0.5);
  animation: slide 3s linear infinite;
}

/* 滑动动画 */
@keyframes slide {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(200%);
  }
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .animated-line-container {
    background-color: rgba(255, 255, 255, 0.1);
  }

  .animated-line {
    box-shadow: 0 0 10px rgba(24, 144, 255, 0.7);
  }
}

</style>